<template>
  <div style="margin-left: 2%;margin-right: 2%;margin-top: 10px">
    <el-card>
      <span style="font-size: 13px">项目编号：</span>
      <el-input  v-model="search.projectCode" placeholder="输入内容" style="width: 130px"></el-input>
      <span style="font-size: 13px;margin-left: 3%">项目名称：</span>
      <el-input  v-model="search.projectName" placeholder="输入内容" style="width: 130px"></el-input>
      <span style="font-size: 13px;margin-left: 3%">采购类别：</span>
      <el-select v-model="search.purchaseCategoryId"  placeholder="请选择" >
        <el-option label="货物类" value="1"></el-option>
        <el-option label="服务类" value="2"></el-option>
        <el-option label="工程类" value="3"></el-option>
      </el-select>
      <div style="display: inline;margin-left: 10%">
        <el-button  size="mini" type="primary" @click="searchConditon">查询</el-button>
        <el-button size="mini" @click="clearMes">清空查询</el-button>
      </div>
    </el-card>
    <div style="margin-top: .8%;text-align: right">
      <el-button size="mini" type="primary" @click="indexAddDialog = true;uploadProgress = false;uploadProgresss = false">添加项目</el-button>
    </div>
    <div style="margin-top: 7px;margin-bottom: 10px">
      <el-table
              :data="itemTable"
              border
              :max-height="tableHeight"
              style="width: 100%">
        <el-table-column
                prop="projectCode"
                min-width="30px"
                label="项目编号"
        >
        </el-table-column>
        <el-table-column
                prop="projectName"
                min-width="40px"
                label="项目名称"
        >
        </el-table-column>
        <el-table-column
                prop="purchaseCategoryId"
                min-width="30px"
                label="采购类别"
        >
          <template slot-scope="scope">
            <!-- 根据采购类别的值显示不同文本 -->
            <span v-if="scope.row.purchaseCategoryId === 1">货物类</span>
            <span v-else-if="scope.row.purchaseCategoryId === 2">服务类</span>
            <span v-else-if="scope.row.purchaseCategoryId === 3">工程类</span>
            <span v-else>其他采购类别</span>
          </template>
        </el-table-column>
        <el-table-column
                prop="purchaseMethod"
                min-width="30px"
                label="采购方式"
        >
        </el-table-column>
        <el-table-column
                prop="budget"
                min-width="40px"
                label="预算金额(元)">
        </el-table-column>
        <el-table-column
                prop="qualificationApproval"
                width="140px"
                label="资格条件审批"
        >
          <template v-if="scope.row.quaSubmitStatus!==null && scope.row.quaApproveStatus !== null" slot-scope="scope">
            <!-- 获取每一行的quaSubmitStatus和quaApproveStatus -->
            <span>{{ scope.row.quaSubmitStatus }} ({{ scope.row.quaApproveStatus }})</span>
          </template>
        </el-table-column>
        <el-table-column
                prop="supplierApproval"
                width="140px"
                label="成交供应商审批"
        >
          <template v-if="scope.row.supplyerSubmitStatus!==null && scope.row.supplyerApproveStatus !== null" slot-scope="scope">
            <!-- 获取每一行的quaSubmitStatus和quaApproveStatus -->
            <span>{{ scope.row.supplyerSubmitStatus }} ({{ scope.row.supplyerApproveStatus }})</span>
          </template>
        </el-table-column>
        <el-table-column
                prop="contractApproval"
                width="140px"
                label="成交合同审批"
        >
          <template v-if="scope.row.contractSubmitStatus!==null && scope.row.contractApproveStatus !== null" slot-scope="scope">
            <!-- 获取每一行的quaSubmitStatus和quaApproveStatus -->
            <span>{{ scope.row.contractSubmitStatus }} ({{ scope.row.contractApproveStatus }})</span>
          </template>
        </el-table-column>
        <el-table-column
                prop="createTime"
                width="150px"
                label="创建时间"
        >
        </el-table-column>
        <el-table-column
                prop="controls"
                width="170px"
                label="操作"
        >
          <template slot-scope="{$index,row}">
            <i  title="修改" @click="indexModifyDialog=true;uploadProgressss = false;uploadProgresssss = false; indexModify(row)" v-if="row.quaSubmitStatus === '未提交'" style="color: dodgerblue;margin-right: 10px;cursor: pointer">修改</i>
            <i  title="删除" @click="indexDel(row)" v-if="row.quaSubmitStatus === '未提交'" style="color: dodgerblue;margin-right: 10px;cursor: pointer">删除</i>
            <i  title="项目管理" @click="goToProjectManagement(row)" style="color: dodgerblue;cursor: pointer;margin-right: 10px">项目管理</i>
            <i  title="修改" @click="detailDialog=true; indexModify(row)" v-if="row.quaSubmitStatus === '已提交'" style="color: dodgerblue;margin-right: 10px;cursor: pointer">查看详情</i>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="theData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!--分页-->
    <!--        <pagination :total="total"-->
    <!--                    style="float: right;margin-top: -.7%"-->
    <!--                    v-show="!showPageSearch"-->
    <!--                    :current-page="theData.page"-->
    <!--                    :page-size="theData.pageSize"-->
    <!--                    @currentChange="getGetItemSizeCurr"-->
    <!--                    @editPagesizes="getGetItemSize"/>-->
    <!--        <pagination :total="total"-->
    <!--                    style="float: right;margin-top: .7%"-->
    <!--                    v-show="showPageSearch"-->
    <!--                    :current-page="theData.page"-->
    <!--                    :page-size="theData.pageSize"-->
    <!--                    @currentChange="getGetItemSizeCurrChange"-->
    <!--                    @editPagesizes="getGetItemSizeChange"/>-->
    <!--添加-->
    <el-dialog
        title="添加"
        :visible.sync="indexAddDialog"
        width="60%"
        center>
      <el-form ref="addItem" :rules="rules" :model="addItem" label-width="200px">
<!--        <el-form-item label="项目编号" prop="projectCode">-->
<!--          <el-input  v-model="addItem.projectCode" placeholder="输入内容"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="项目名称" prop="projectName">
          <el-input  v-model="addItem.projectName" placeholder="输入内容" style="width: 87%"></el-input>
        </el-form-item>
        <el-form-item label="采购类别" prop="purchaseCategoryId">
          <el-select v-model="addItem.purchaseCategoryId"  placeholder="请选择" style="width: 87%">
            <el-option label="货物类" value="1"></el-option>
            <el-option label="服务类" value="2"></el-option>
            <el-option label="工程类" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="采购方式"  prop="purchaseMethod">线下</el-form-item>
        <el-form-item label="预算金额" prop="budget">
          <el-input  v-model="addItem.budget" placeholder="输入内容" @input="checkInput(addItem,'budget')" style="width: 87%"></el-input>
          <span style="margin-left: 10px;">元</span>
        </el-form-item>
        <el-form-item label="会议纪要文件" prop="meetingMinutes">
          <div style="width: 87%; float: left">
            <el-input v-model="addItem.meetingMinutesValue" placeholder="选择文件" readonly></el-input>
          </div>
          <div style="float: right">
            <el-button type="primary" v-if="!uploadProgress" @click="handleUploadClick">上传</el-button>
            <input ref="fileInput" type="file" style="display: none" @change="handleFileChange">
          </div>
          <el-progress style="float:right" v-if="uploadProgress" width="45" type="circle" :percentage="progress"></el-progress>
        </el-form-item>
        <el-form-item label="项目前期资料(财政批复)" prop="preFile">
          <div style="width: 87%; float: left">
            <el-input v-model="addItem.preFileValue" placeholder="选择文件" readonly></el-input>
          </div>
          <div style="float: right">
            <el-button type="primary" v-if="!uploadProgresss" @click="handleUploadCClick">上传</el-button>
            <input ref="preFileInput" type="file" style="display: none" @change="handlePreFileChange">
          </div>
          <el-progress style="float:right" v-if="uploadProgresss" width="45" type="circle" :percentage="progresss"></el-progress>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button @click="indexSubmitAdd" type="primary" style="margin-left: 20px">确 定</el-button>
        <el-button @click="indexCancelAdd">取 消</el-button>
      </div>
    </el-dialog>
    <!--修改-->
    <el-dialog
        title="修改"
        :visible.sync="indexModifyDialog"
        width="40%"
        center>
      <el-form ref="modItem" :rules="rules" :model="modItem" label-width="100px">
<!--        <el-form-item label="项目编号" prop="projectCode">-->
<!--          <el-input  v-model="modItem.projectCode" placeholder="输入内容"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="项目名称" prop="projectName">
          <el-input  v-model="modItem.projectName" placeholder="输入内容" style="width: 74%"></el-input>
        </el-form-item>
        <el-form-item  label="采购方式"  prop="purchaseMethod">线下</el-form-item>
        <el-form-item label="预算金额" prop="budget">
          <el-input  v-model="modItem.budget" placeholder="输入内容" @input="checkInput(modItem,'budget')" style="width: 74%"></el-input>
          <span style="margin-left: 10px;">元</span>
        </el-form-item>
        <el-form-item label="会议纪要文件" prop="meetingMinutes">
          <span style="width: 74%;float: left;cursor: pointer" @click="downloadMMinutesPDF">{{this.modItem.meetingMinutesValue}}</span>
          <div style="float: right">
            <el-button type="primary" v-if="!uploadProgressss" @click="handleUploadClick">重新上传</el-button>
            <input ref="fileInput" type="file" style="display: none" @change="handleFileCChange">
          </div>
          <el-progress style="float:right" v-if="uploadProgressss" width="45" type="circle" :percentage="progressss"></el-progress>
        </el-form-item>
        <el-form-item label="项目前期资料(财政批复)" prop="preFile">
          <span style="width: 74%;float: left;cursor: pointer" @click="downloadPreFilePDF">{{this.modItem.preFileValue}}</span>
          <div style="float: right">
            <el-button type="primary" v-if="!uploadProgresssss" @click="handleUploadCClick">重新上传</el-button>
            <input ref="preFileInput" type="file" style="display: none" @change="handlePreFileCChange">
          </div>
          <el-progress style="float:right" v-if="uploadProgresssss" width="45" type="circle" :percentage="progresssss"></el-progress>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button @click="indexSubmitModify" type="primary" style="margin-left: 20px">确 定</el-button>
        <el-button @click="indexCancelModify">取 消</el-button>
      </div>
    </el-dialog>
    <!--查看详情-->
    <el-dialog
            title="查看详情"
            :visible.sync="detailDialog"
            width="40%"
            center>
      <el-form ref="modItem" :rules="rules" :model="modItem" label-width="220px">
        <!--        <el-form-item label="项目编号" prop="projectCode">-->
        <!--          <el-input  v-model="modItem.projectCode" placeholder="输入内容"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="项目名称：" prop="projectName">{{this.modItem.projectName}}</el-form-item>
        <el-form-item  label="采购方式："  prop="purchaseMethod">线下</el-form-item>
        <el-form-item label="预算金额：" prop="budget">
          {{this.modItem.budget}}
          <span style="margin-left: 10px;">元</span>
        </el-form-item>
        <el-form-item label="会议纪要文件：" prop="meetingMinutes">
          <span style="width: 74%;float: left;cursor: pointer" @click="downloadMMinutesPDF">{{this.modItem.meetingMinutesValue}}</span>
        </el-form-item>
        <el-form-item label="项目前期资料(财政批复)：" prop="preFile">
          <span style="width: 74%;float: left;cursor: pointer" @click="downloadPreFilePDF">{{this.modItem.preFileValue}}</span>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button @click="indexCancelModify">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img src="./purchase.jpg" alt="图片" style="width: 100%;height: 100%;"/>
    </el-dialog>
  </div>
</template>

<script>
  import {
    reqPurchaseList,
    reqGetAllItems,
    reqConditionSer,
    reqNegativeKeywords,
    reqManageAdd,
    reqManageDel,
    reqManageModify,
    reqApproveSave,
    reqApproveSubmit,
    reqApproveGet,
    reqApproveCheck,
    reqProjectAdd,
    uploadFile,
    reqProjectModify,
    reqProjectContent,
    reqProjectDel,
    uploadPrefile,
    downloadMeetingMinutes,
    downloadPreFile
  } from "@/api/purchaseItemManage";
import {deleteNegativeKey} from "@/api/condition/negativeKey";
  import {serverIp} from "../../../public/config";
  import {downloadContractsFile} from "@/api/concludeContract";
  import downloadFile from "@/utils/downloadFile";


export default {
  name: "index",
  data(){
    return{
      search:{
        projectCode:'',
        projectName:'',
        purchaseCategoryId:''
      },
      addItem: {
        projectCode: '',
        projectName: '',
        purchaseCategoryId: '',
        budget:'',
        meetingMinutesValue: '',
        meetingMinutes: null,
        preFileValue: '',
        preFile: null
      },
      modItem: {
        projectCode: '',
        projectName: '',
        budget:'',
        meetingMinutesValue:'',
        preFileValue:'',
        meetingMinutes: null,
        preFile: null
      },
      theData:{
        page: 1,
        pageSize: 20,
      },
      rules: {
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        purchaseCategoryId: [{ required: true, message: '请选择采购类别', trigger: 'change' }],
        budget: [{ required: true, message: '请输入预算金额', trigger: 'blur' }],
      },
      ProjectId:'',
      TotalMoney:'',
      currentPage: 1,
      indexAddDialog: false,
      indexModifyDialog: false,
      detailDialog: false,
      showPageSearch: false,
      loading:true,
      pageflag:false,
      total: 0,
      itemTable:[],
      dialogVisible: false,
      meetingMinutesUploaded: false,
      preFileUploaded: false,
      progress: 0,
      progresss: 0,
      progressss: 0,
      progresssss: 0,
      uploadProgress: false,
      uploadProgresss: false,
      uploadProgressss: false,
      uploadProgresssss: false,
      tableHeight: 200,
    }
  },
  mounted() {
    this.getAllitems();
  },
  created() {
    this.tableHeight = window.innerHeight - 350;
  },
  methods: {
    //获取所有项目
    async getAllitems(){
      let res =await reqGetAllItems()
      console.log(res)
      if(res.data.code===200){
        this.itemTable = res.data.data.records.map(item => {
          return { ...item, projectId: item.projectId };
        });
        this.total = res.data.data.total;
      }else {
        this.$message.error(res.data.msg);
      }
    },

    //查询
    async searchConditon() {
      this.loading = true
      let theDatas = {
        projectCode:this.search.projectCode,
        projectName:this.search.projectName || '',
        purchaseCategoryId:this.search.purchaseCategoryId,
      }
      if(!this.pageflag){
        this.currentPage = 1;
      }
      let pageInfo = this.currentPage + "/" + this.theData.pageSize
      let res = await reqConditionSer(pageInfo,theDatas)
      this.showPageSearch=true
      if (res) {
        this.loading = false
      }
      if(res.data.code===200){
        this.itemTable = res.data.data.record;
        this.total=res.data.data.total
      }else {
          this.itemTable = [];
          this.total = 0;
          this.$message(res.data.msg);
        };
      this.pageflag = false
      },
    clearMes(){
      this.showPageSearch=false
      Object.keys(this.search).forEach(index=>this.search[index]='')
    },
    handleSizeChange(val) {
      this.theData.pageSize = val
      this.searchConditon()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageflag = true
      this.searchConditon()
    },

    //跳转到项目管理
    goToProjectManagement(row) {
      this.$router.push({
        name: 'itemManage',
        params: {
          projectId: row.projectId,
          projectCode: row.projectCode,
          projectName: row.projectName,
          purchaseCategoryId: row.purchaseCategoryId,
          budget: row.budget,
        },
      });
    },

    //会议纪要文件选择、重新上传文件选择、前期资料文件选择
    handleUploadClick() {
      this.$refs.fileInput.click();
    },
    handleUploadCClick() {
      this.$refs.preFileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];

      this.addItem.meetingMinutes = file;

      const fileInputValue = file.name;
      this.$set(this.addItem, 'meetingMinutesValue', fileInputValue);
    },
    handlePreFileChange(event) {
      const file = event.target.files[0];

      this.addItem.preFile = file;

      const fileInputValue = file.name;
      this.$set(this.addItem, 'preFileValue', fileInputValue);
    },
    handleFileCChange(event) {
      const file = event.target.files[0];

      this.modItem.meetingMinutes = file;

      const fileInputValue = file.name;
      this.$set(this.modItem, 'meetingMinutesValue', fileInputValue);
    },
    handlePreFileCChange(event) {

      const file = event.target.files[0];

      this.modItem.preFile = file;

      const fileInputValue = file.name;
      this.$set(this.modItem, 'preFileValue', fileInputValue);
    },

    //点击下载未修改前文件
    async downloadMMinutesPDF() {
      let res = await downloadMeetingMinutes(this.ProjectId)
      downloadFile(res,this.modItem.meetingMinutesValue)
    },
    async downloadPreFilePDF() {
      let res = await downloadPreFile(this.ProjectId)
      downloadFile(res,this.modItem.preFileValue)
    },

    //预算金额禁止输入非数字
    checkInput(object, field) {
      const value = object[field];
      if (isNaN(value)) {
        this.showInputError();
        object[field] = '';
      }
    },
    showInputError() {
      this.$message({
        message: '请输入数字',
        type: 'warning',
      });
    },

    //添加项目
    async indexSubmitAdd() {
        this.$refs.addItem.validate(async (valid) => {
          if (valid) {
            if (this.addItem.meetingMinutes) {
              const file = this.addItem.meetingMinutes;
              const maxSize = 200 * 1024 * 1024; // 200M
              const allowedExtensions = ['pdf']; // 只能上传PDF
              if (file.size > maxSize) {
                this.$message.error('文件大小超过限制（最大200M）');
                return;
              }
              const fileExtension = file.name.split('.').pop().toLowerCase();
              if (!allowedExtensions.includes(fileExtension)) {
                this.$message.error('只能上传PDF文件');
                return;
              }
              this.uploadProgress = true
              const formData = new FormData();
              formData.append('file', file);
              formData.append('projectId', '');
              const xhr = new XMLHttpRequest();
              xhr.open('POST', `${serverIp}/project/upload`);
              const token = localStorage.getItem("token")
              xhr.setRequestHeader('Authorization', token)
              xhr.upload.addEventListener('progress', (event) => {
                if (event.lengthComputable) {
                  const percent = Math.round((event.loaded / event.total) * 100);
                  this.progress = percent;
                }
              });
              xhr.onreadystatechange = async () => {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                  if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 200) {
                      const projectIdFromResponse = response.data.projectId;
                      if (this.addItem.preFile) {
                        const file = this.addItem.preFile;
                        const maxSize = 200 * 1024 * 1024; // 200M
                        const allowedExtensions = ['pdf']; // 只能上传PDF
                        if (file.size > maxSize) {
                          this.$message.error('文件大小超过限制（最大200M）');
                          return;
                        }
                        const fileExtension = file.name.split('.').pop().toLowerCase();
                        if (!allowedExtensions.includes(fileExtension)) {
                          this.$message.error('只能上传PDF文件');
                          return;
                        }
                        this.uploadProgresss = true
                        const formData = new FormData();
                        formData.append('file', file);
                        formData.append('projectId', projectIdFromResponse);
                        const xhr = new XMLHttpRequest();
                        xhr.open('POST', `${serverIp}/project/uploadPreFiles`);
                        const token = localStorage.getItem("token")
                        xhr.setRequestHeader('Authorization', token)
                        xhr.upload.addEventListener('progress', (event) => {
                          if (event.lengthComputable) {
                            const percent = Math.round((event.loaded / event.total) * 100);
                            this.progresss = percent;
                          }
                        });
                        xhr.onreadystatechange = async () => {
                          if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                              const response = JSON.parse(xhr.responseText);
                              if (response.code === 200) {
                                const inputObj = {
                                  projectId: response.data.projectId,
                                  projectName: this.addItem.projectName,
                                  purchaseCategoryId: this.addItem.purchaseCategoryId,
                                  budget: this.addItem.budget,
                                  flag: 1,
                                }
                                let res = await reqProjectAdd(inputObj)
                                if (res.data.code === 200) {
                                  this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                  });
                                  await this.getAllitems()
                                  this.addItem = {
                                    projectName: '',
                                    purchaseCategoryId: '',
                                    budget: '',
                                    meetingMinutesValue: '',
                                    preFileValue: ''
                                  };
                                  this.$refs["addItem"].resetFields();
                                  this.indexAddDialog = false;
                                  this.uploadProgress = false
                                  this.uploadProgresss = false
                                } else if (res.data.code === 456) {
                                  this.$message({
                                    type: 'error',
                                    message: res.data.msg
                                  })
                                  this.openImgDialog()
                                } else {
                                  this.$message.error(res.data.msg);
                                  this.uploadProgress = false
                                  this.uploadProgresss = false
                                }
                              } else {
                                this.$message.error('文件上传失败');
                                this.uploadProgress = false
                                this.uploadProgresss = false
                              }
                            } else {
                              this.$message.error('网络请求失败');
                              this.uploadProgress = false
                              this.uploadProgresss = false
                            }
                          }
                        };
                        xhr.send(formData);
                      } else {
                        const inputObj = {
                          projectId: response.data.projectId,
                          projectName: this.addItem.projectName,
                          purchaseCategoryId: this.addItem.purchaseCategoryId,
                          budget: this.addItem.budget,
                          flag: 1,
                        }
                        let ress = await reqProjectAdd(inputObj)
                        if (ress.data.code === 200) {
                          this.$message({
                            type: 'success',
                            message: '添加成功!'
                          });
                          await this.getAllitems()
                          this.addItem = {
                            projectName: '',
                            purchaseCategoryId: '',
                            budget: '',
                            meetingMinutesValue: '',
                            preFileValue: ''
                          };
                          this.$refs["addItem"].resetFields();
                          this.indexAddDialog = false;
                          this.uploadProgress = false
                        } else if (ress.data.code === 456) {
                          this.$message({
                            type: 'error',
                            message: ress.data.msg
                          })
                          this.openImgDialog()
                        } else {
                          this.$message.error(ress.data.msg);
                          this.uploadProgress = false
                        }
                      }
                    } else {
                      this.$message.error('文件上传失败');
                      this.uploadProgress = false
                    }
                  } else {
                    this.$message.error('网络请求失败');
                    this.uploadProgress = false
                  }
                }
              };
              xhr.send(formData);
            } else if (this.addItem.preFile) {
              const file = this.addItem.preFile;
              const maxSize = 200 * 1024 * 1024; // 200M
              const allowedExtensions = ['pdf']; // 只能上传PDF
              if (file.size > maxSize) {
                this.$message.error('文件大小超过限制（最大200M）');
                return;
              }
              const fileExtension = file.name.split('.').pop().toLowerCase();
              if (!allowedExtensions.includes(fileExtension)) {
                this.$message.error('只能上传PDF文件');
                return;
              }
              this.uploadProgresss = true
              const formData = new FormData();
              formData.append('file', file);
              formData.append('projectId', '');
              const xhr = new XMLHttpRequest();
              xhr.open('POST', `${serverIp}/project/uploadPreFiles`);
              const token = localStorage.getItem("token")
              xhr.setRequestHeader('Authorization', token)
              xhr.upload.addEventListener('progress', (event) => {
                if (event.lengthComputable) {
                  const percent = Math.round((event.loaded / event.total) * 100);
                  this.progresss = percent;
                }
              });
              xhr.onreadystatechange = async () => {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                  if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 200) {
                      const inputObj = {
                        projectId: response.data.projectId,
                        projectName: this.addItem.projectName,
                        purchaseCategoryId: this.addItem.purchaseCategoryId,
                        budget: this.addItem.budget,
                      }
                      let resss = await reqProjectAdd(inputObj)
                      if (resss.data.code === 200) {
                        this.$message({
                          type: 'success',
                          message: '添加成功!'
                        });
                        await this.getAllitems()
                        this.addItem = {
                          projectName: '',
                          purchaseCategoryId: '',
                          budget: '',
                          meetingMinutesValue: '',
                          preFileValue: ''
                        };
                        this.$refs["addItem"].resetFields();
                        this.indexAddDialog = false;
                        this.uploadProgresss = false
                      } else if (resss.data.code === 456) {
                        this.$message({
                          type: 'error',
                          message: resss.data.msg
                        })
                        this.openImgDialog()
                      } else {
                        this.$message.error(resss.data.msg);
                        this.uploadProgresss = false
                      }
                    } else {
                      this.$message.error('文件上传失败');
                      this.uploadProgresss = false
                    }
                  } else {
                    this.$message.error('网络请求失败');
                    this.uploadProgresss = false
                  }
                }
              };
              xhr.send(formData);
            } else {
              const inputObj = {
                projectId: null,
                projectName: this.addItem.projectName,
                purchaseCategoryId: this.addItem.purchaseCategoryId,
                budget: this.addItem.budget,
              }
              let ressss = await reqProjectAdd(inputObj)
              if (ressss.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                await this.getAllitems()
                this.addItem = {
                  projectName: '',
                  purchaseCategoryId: '',
                  budget: '',
                  meetingMinutesValue: '',
                  preFileValue: ''
                };
                this.$refs["addItem"].resetFields();
                this.indexAddDialog = false;
              } else if (ressss.data.code === 456) {
                this.$message({
                  type: 'error',
                  message: ressss.data.msg
                })
                this.openImgDialog()
              } else {
                this.$message.error(ressss.data.msg);
              }
            }
          }
        });
    },

    //弹窗政府采购流程
    openImgDialog() {
      this.dialogVisible = true
    },

    //取消添加项目
    indexCancelAdd() {
      this.addItem = {
        projectName: '',
        purchaseCategoryId: '',
        budget:'',
        meetingMinutesValue: '',
      };
      this.$refs["addItem"].resetFields();
      this.indexAddDialog = false;
    },

    //点击修改展示未修改前内容
    async indexModify(row) {

      this.ProjectId = row.projectId //获取当前项目projectId
      this.modItem.projectName = row.projectName
      this.modItem.budget = row.budget
      let res = await reqProjectContent(this.ProjectId)
      if(res.data.code===200){
        this.modItem.meetingMinutesValue = res.data.data.filename
        this.modItem.preFileValue = res.data.data.filenameP
        location.clear();
      }
    },

    //修改项目
    async indexSubmitModify() {
      const tempProjectId = this.ProjectId;
      this.$refs.modItem.validate(async (valid) => {
        if (valid) {
          if (this.modItem.meetingMinutes) {
            const file = this.modItem.meetingMinutes;
            const maxSize = 200 * 1024 * 1024; // 200M
            const allowedExtensions = ['pdf']; // 只能上传PDF
            if (file.size > maxSize) {
              this.$message.error('文件大小超过限制（最大200M）');
              return;
            }
            const fileExtension = file.name.split('.').pop().toLowerCase();
            if (!allowedExtensions.includes(fileExtension)) {
              this.$message.error('只能上传PDF文件');
              return;
            }
            this.uploadProgressss = true
            const formData = new FormData();
            formData.append('file', file);
            formData.append('projectId', this.ProjectId);
            const xhr = new XMLHttpRequest();
            xhr.open('POST', `${serverIp}/project/upload`);
            const token = localStorage.getItem("token")
            xhr.setRequestHeader('Authorization', token)
            xhr.upload.addEventListener('progress', (event) => {
              if (event.lengthComputable) {
                const percent = Math.round((event.loaded / event.total) * 100);
                this.progressss = percent;
              }
            });
            xhr.onreadystatechange = async () => {
              if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                  const response = JSON.parse(xhr.responseText);
                  if (response.code === 200) {
                    const projectIdFromResponse = response.data.projectId;
                    if (this.modItem.preFile) {
                      const file = this.modItem.preFile;
                      const maxSize = 200 * 1024 * 1024; // 200M
                      const allowedExtensions = ['pdf']; // 只能上传PDF
                      if (file.size > maxSize) {
                        this.$message.error('文件大小超过限制（最大200M）');
                        return;
                      }
                      const fileExtension = file.name.split('.').pop().toLowerCase();
                      if (!allowedExtensions.includes(fileExtension)) {
                        this.$message.error('只能上传PDF文件');
                        return;
                      }
                      this.uploadProgresssss = true
                      const formData = new FormData();
                      formData.append('file', file);
                      formData.append('projectId', projectIdFromResponse);
                      const xhr = new XMLHttpRequest();
                      xhr.open('POST', `${serverIp}/project/uploadPreFiles`);
                      const token = localStorage.getItem("token")
                      xhr.setRequestHeader('Authorization', token)
                      xhr.upload.addEventListener('progress', (event) => {
                        if (event.lengthComputable) {
                          const percent = Math.round((event.loaded / event.total) * 100);
                          this.progresssss = percent;
                        }
                      });
                      xhr.onreadystatechange = async () => {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                          if (xhr.status === 200) {
                            const response = JSON.parse(xhr.responseText);
                            if (response.code === 200) {
                              const inputObj = {
                                projectId: response.data.projectId,
                                projectName: this.modItem.projectName,
                                purchaseCategoryId: this.modItem.purchaseCategoryId,
                                budget: this.modItem.budget,
                                flag: 1,
                              }
                              let res = await reqProjectModify(inputObj)
                              if (res.data.code === 200) {
                                this.$message({
                                  type: 'success',
                                  message: '修改成功!'
                                });
                                await this.getAllitems()
                                this.modItem = {
                                  projectName: '',
                                  purchaseCategoryId: '',
                                  budget: '',
                                  meetingMinutesValue: '',
                                  preFileValue: ''
                                };
                                this.$refs["modItem"].resetFields();
                                this.indexModifyDialog = false;
                                this.uploadProgressss = false
                                this.uploadProgresssss = false
                              } else if (res.data.code === 456) {
                                this.$message({
                                  type: 'error',
                                  message: res.data.msg
                                })
                                this.openImgDialog()
                              } else {
                                this.$message.error(res.data.msg);
                                this.uploadProgressss = false
                                this.uploadProgresssss = false
                              }
                            } else {
                              this.$message.error('文件上传失败');
                              this.uploadProgressss = false
                              this.uploadProgresssss = false
                            }
                          } else {
                            this.$message.error('网络请求失败');
                            this.uploadProgressss = false
                            this.uploadProgresssss = false
                          }
                        }
                      };
                      xhr.send(formData);
                    } else {
                      const inputObj = {
                        projectId: response.data.projectId,
                        projectName: this.modItem.projectName,
                        purchaseCategoryId: this.modItem.purchaseCategoryId,
                        budget: this.modItem.budget,
                        flag: 1,
                      }
                      let ress = await reqProjectModify(inputObj)
                      if (ress.data.code === 200) {
                        this.$message({
                          type: 'success',
                          message: '修改成功!'
                        });
                        await this.getAllitems()
                        this.modItem = {
                          projectName: '',
                          purchaseCategoryId: '',
                          budget: '',
                          meetingMinutesValue: '',
                          preFileValue: ''
                        };
                        this.$refs["modItem"].resetFields();
                        this.indexModifyDialog = false;
                        this.uploadProgressss = false
                      } else if (ress.data.code === 456) {
                        this.$message({
                          type: 'error',
                          message: ress.data.msg
                        })
                        this.openImgDialog()
                      } else {
                        this.$message.error(ress.data.msg);
                        this.uploadProgressss = false
                      }
                    }
                  } else {
                    this.$message.error('文件上传失败');
                    this.uploadProgressss = false
                  }
                } else {
                  this.$message.error('网络请求失败');
                  this.uploadProgressss = false
                }
              }
            };
            xhr.send(formData);
          } else if (this.modItem.preFile) {
            const file = this.modItem.preFile;
            const maxSize = 200 * 1024 * 1024; // 200M
            const allowedExtensions = ['pdf']; // 只能上传PDF
            if (file.size > maxSize) {
              this.$message.error('文件大小超过限制（最大200M）');
              return;
            }
            const fileExtension = file.name.split('.').pop().toLowerCase();
            if (!allowedExtensions.includes(fileExtension)) {
              this.$message.error('只能上传PDF文件');
              return;
            }
            this.uploadProgresssss = true
            const formData = new FormData();
            formData.append('file', file);
            formData.append('projectId', this.ProjectId);
            const xhr = new XMLHttpRequest();
            xhr.open('POST', `${serverIp}/project/uploadPreFiles`);
            const token = localStorage.getItem("token")
            xhr.setRequestHeader('Authorization', token)
            xhr.upload.addEventListener('progress', (event) => {
              if (event.lengthComputable) {
                const percent = Math.round((event.loaded / event.total) * 100);
                this.progresssss = percent;
              }
            });
            xhr.onreadystatechange = async () => {
              if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                  const response = JSON.parse(xhr.responseText);
                  if (response.code === 200) {
                    const inputObj = {
                      projectId: response.data.projectId,
                      projectName: this.modItem.projectName,
                      purchaseCategoryId: this.modItem.purchaseCategoryId,
                      budget: this.modItem.budget,
                    }
                    let resss = await reqProjectModify(inputObj)
                    if (resss.data.code === 200) {
                      this.$message({
                        type: 'success',
                        message: '修改成功!'
                      });
                      await this.getAllitems()
                      this.modItem = {
                        projectName: '',
                        purchaseCategoryId: '',
                        budget: '',
                        meetingMinutesValue: '',
                        preFileValue: ''
                      };
                      this.$refs["modItem"].resetFields();
                      this.indexModifyDialog = false;
                      this.uploadProgresssss = false
                    } else if (resss.data.code === 456) {
                      this.$message({
                        type: 'error',
                        message: resss.data.msg
                      })
                      this.openImgDialog()
                    } else {
                      this.$message.error(resss.data.msg);
                      this.uploadProgresssss = false
                    }
                  } else {
                    this.$message.error('文件上传失败');
                    this.uploadProgresssss = false
                  }
                } else {
                  this.$message.error('网络请求失败');
                  this.uploadProgresssss = false
                }
              }
            };
            xhr.send(formData);
          }else{
            const inputObj = {
              projectId: tempProjectId,
              projectName: this.modItem.projectName,
              budget: this.modItem.budget,
            }
            let res =await reqProjectModify(inputObj)
            if(res.data.code===200){
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
              await this.getAllitems()
              this.indexModifyDialog = false;
            }else if (res.data.code === 456) {
              this.$message({
                type: 'error',
                message: res.data.msg
              })
              this.openImgDialog()
            }else {
              this.$message.error(res.data.msg);
            }
           }
          }
      });
    },

    //取消修改项目
    indexCancelModify() {
      this.modItem = {
        projectName: '',
        budget:'',
        meetingMinutesValue: '',
        preFileValue: ''
      },
      this.$refs["modItem"].resetFields();
      this.indexModifyDialog = false;
      this.detailDialog = false;
    },

    //删除项目
    async indexDel(row) {
      let res =await reqProjectDel(row.projectId)
      if(res.data.code===200){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        await this.getAllitems()
      }else {
        this.$message.error(res.data.msg);
      }
    }
  }
}
</script>

<style scoped>
  @keyframes moveOut {
    0% {
      transform: translateX(0);
      opacity: 1;
    }
    100% {
      transform: translateX(-100%);
      opacity: 0;
    }
  }

  @keyframes moveIn {
    0% {
      transform: translateX(100%);
      opacity: 0;
    }
    100% {
      transform: translateX(0);
      opacity: 1;
    }
  }
</style>
